﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FurionFrame.Common.Helper
{
    public static class HexHelper
    {
        /// <summary>
        /// 从字符串转换到16进制表示的字符串
        /// </summary>
        /// <param name="s">从字符串转换到16进制表示的字符串</param>
        /// <param name="charset">编码,如"utf-8","gb2312"</param>
        /// <param name="split">是否每字符用空格分隔</param>
        /// <returns></returns>
        public static string ToHex(string s, string charset = "gb2312", bool split = true)
        {
            if ((s.Length % 2) != 0)
            {
                s += " ";
            }
            var chs = Encoding.GetEncoding(charset);
            var bytes = chs.GetBytes(s);
            var str = "";
            for (var i = 0; i < bytes.Length; i++)
            {
                var xNum = $"{bytes[i]:X}";
                str += xNum.Length == 2 ? xNum : $"0{xNum}";
                if (split && (i != bytes.Length - 1))
                {
                    str += " ";
                }
            }
            return str.ToUpper();
        }
        /// <summary>
        /// 转换到16进制表示的字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="split"></param>
        /// <returns></returns>
        public static string ToHex(byte[] bytes, bool split = true)
        {
            var str = "";
            for (var i = 0; i < bytes.Length; i++)
            {
                var xNum = $"{bytes[i]:X}";
                str += xNum.Length == 2 ? xNum : $"0{xNum}";
                if (split && (i != bytes.Length - 1))
                {
                    str += " ";
                }
            }
            return str.ToUpper();
        }
        /// <summary>
        /// StreamToBytes
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static byte[] StreamToBytes(Stream stream)
        {
            var bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);

            // 设置当前流的位置为流的开始 
            stream.Seek(0, SeekOrigin.Begin);
            return bytes;
        }
        /// <summary>
        /// BytesToStream
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static Stream BytesToStream(byte[] bytes)
        {
            Stream stream = new MemoryStream(bytes);
            return stream;
        }
        /// <summary>
        /// 从16进制转换成utf编码的字符串
        /// </summary>
        /// <param name="hex">从16进制转换成utf编码的字符串</param>
        /// <param name="charset">编码,如"utf-8","gb2312"</param>
        /// <returns></returns>
        public static string UnHex(string hex, string charset = "gb2312")
        {
            if (hex == null)
                throw new ArgumentNullException("hex");
            hex = hex.Replace(",", "");
            hex = hex.Replace("\n", "");
            hex = hex.Replace("\\", "");
            hex = hex.Replace(" ", "");
            if (hex.Length % 2 != 0)
            {
                hex += "20";//空格
                // throw new ArgumentException("hex is not a valid number!", "hex");
            }
            // 需要将 hex 转换成 byte 数组。
            var bytes = new byte[hex.Length / 2];
            for (var i = 0; i < bytes.Length; i++)
            {
                try
                {
                    // 每两个字符是一个 byte。
                    bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
                    System.Globalization.NumberStyles.HexNumber);
                }
                catch
                {
                    // Rethrow an exception with custom message.
                    throw new ArgumentException("hex is not a valid hex number!", "hex");
                }
            }
            var chs = Encoding.GetEncoding(charset);
            return chs.GetString(bytes);
        }
    }
}
